import socket
import threading

# 定义服务器和客户端地址和端口
SERVER_ADDRESS = '[::]'
PORT = 3000
DST_HOST = 'localhost'
DST_PORT = 11434
def forward(src, dest):
    size = 4096 # 缓冲区大小
    while True:
        data = src.recv(size)
        if not data:
            break
        dest.sendall(data)

# 创建套接字并绑定到服务器地址和端口
server_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
server_socket.bind((SERVER_ADDRESS, PORT))

print("Server running on port %s" %PORT)

while True:
    server_socket.listen(1)
    
    # 接受客户端连接
    client_conn, addr = server_socket.accept()
    print('Connected by', addr)
    
    # 创建一个新的套接字用于转发数据
    forwarder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    forwarder.connect((DST_HOST, DST_PORT)) # 连接到另一个端口
    
    print("Starting to forward data")
    t1 = threading.Thread(target=forward, args=(client_conn, forwarder))
    t2 = threading.Thread(target=forward, args=(forwarder, client_conn))
    
    # 启动线程
    t1.start()
    t2.start()